chrome.extension.sendRequest( { showPageAction: true } );

var showingMode = 0; // 0 = all, 1 = public, 2 = private
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
	if (!request) {
		sendResponse();
		return;
	}
	
	if (request.toggleShowingMode) {
		showingMode = (showingMode + 1) % 3;
		updateImageSrcs();
		sendResponse();
		return;
	}

	if (request.getShowingMode) {
		sendResponse(showingMode == 0 ? "all" :
			showingMode == 1 ? "public" :
			showingMode == 2 ? "private" : "???");
		return;
	}
	
	sendResponse();
});

var imgIds = new Array();
var savedImages = { };

var imgs = document.getElementsByClassName("pc_img");
for (var i = 0, img; img = imgs[i]; i++) {
	if (img.tagName != "IMG")
		continue;
	var parent = img.parentNode;
	if (!parent || parent.tagName != "A")
		continue;
	var imgUrl = parent.href;

	var re = new RegExp("/photos/[^/]+/([^/]+)(?:[/^])");
	var match = re.exec(imgUrl);
	if (match.length < 2)
		continue;

	var photoId = match[1];
	imgIds.push(photoId);
	savedImages[photoId] = {
		imageElement: img,
		originalSrc: img.src
	};
	
}
if (imgIds.length > 0)
	chrome.extension.sendRequest( { photoIds: imgIds }, returnedPrivacySettings );
	
function returnedPrivacySettings(privacySettings)
{
	if (!privacySettings)
		return;

	// thinkme: iterate over savedImages or privacySettings here?
	for (var id in savedImages)
		savedImages[id].privacy = privacySettings[id] ? privacySettings[id] : "private";

	updateImageSrcs();
}


function updateImageSrcs()
{
	for (var id in savedImages) {
		if (!savedImages[id].privacy)
			continue;
		
		var privateBackground = "url(" + chrome.extension.getURL("private.png") + ") repeat top left";
		var publicBackground = "url(" + chrome.extension.getURL("public.png") + ") repeat top left";
		var transparentSrc = chrome.extension.getURL("transparent.png");
		
		if (savedImages[id].privacy == "public") {
			savedImages[id].imageElement.style.background = publicBackground;
			savedImages[id].imageElement.src =
				showingMode == 2 ? transparentSrc : savedImages[id].originalSrc;
		}
		else if (savedImages[id].privacy == "private") {
			savedImages[id].imageElement.style.background = privateBackground;
			savedImages[id].imageElement.src =
				showingMode == 1 ? transparentSrc : savedImages[id].originalSrc;
		}
	}

/*	
	for (var i = 0, id; id = obj.publicPhotoIds[i]; i++) {
		var img = idsToElements[id];
		if (img) {
			//img.style.border = "2px dotted green";
			img.src = chrome.extension.getURL("transparent.png");
			var publicBgUrl = chrome.extension.getURL("public.png");
			img.style.background = "url(" + publicBgUrl + ") repeat top left";
			// TODO: need to save orig src so we can replace it when reshowing
		}
	}
*/
}
/*
for (var i = 0; i < imgs.length; i += 2)
	imgs[i].style.border = "2px dotted green";
*/
